递归：

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void print(TreeNode* root, vector<int> &res ) {
        if (root) {
            print(root->left, res);
            print(root->right, res);
            res.push_back(root->val);
        } else return ;
        
    }
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        print(root, res);
        return res;
    }
};

迭代：
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        TreeNode* pre;
        vector<TreeNode*> q;
        vector<int> res;
        while (root || !q.empty()) {
            while (root) {
                q.push_back(root);
                root = root->left;
            }
            if (!q.empty()) {
                TreeNode* top = q.back();
                if (!(top->right) || top->right == pre) {
                    pre = top;
                    res.push_back(top->val);
                    q.pop_back();
                } else {
                    root = top->right;
                }
            }
        }
        return res;
    }
};